package org.xurui.sxl.protocol.command.impl;

import org.jetlinks.core.message.CommonDeviceMessage;
import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.EncodedMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.function.FunctionInvokeMessageReply;
import org.xurui.sxl.protocol.cache.ConcurrentMapCache;
import org.xurui.sxl.protocol.command.CmdCodec;
import org.xurui.sxl.protocol.enums.CommandEnum;
import org.xurui.sxl.protocol.utils.BinaryUtils;
import org.xurui.sxl.protocol.utils.NumberUtils;
import org.xurui.sxl.protocol.utils.SxlMessageUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取设备 IMEI 号
 */
public class CmdCodec_GETIMEID implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.GETIMEID.name().equals(cmd);
    }

    @Override
    public boolean supportsRelayCmd() {
        return true;
    }

    @Override
    public List<DeviceMessage> parsePayload(String payload, FromDeviceMessageContext context) {
        //设备回复格式：*XX,YYYYYYYYYYYYYYY,V4,GETIMEID,seq,HHMMSS,MEID,S,latitude,D,longitude,G,speed,pdop,DDMMYY,tracker_status#
        //设备回复示例：*TJ,86954789991234566958,V4,GETIMEID,130305,130306,8620209163012,V,2230.7021,N,11355.1445,E,0.00,000,271112,FFFFFFFF#
        //参数说明：MEID 设备 IMEI 号
        FunctionInvokeMessageReply report = FunctionInvokeMessageReply.create();
        String[] payloadArr = payload.replaceAll("\\*","").split(",");
        String deviceId = payloadArr[1];
        report.setDeviceId(deviceId);
        Object messageIdObj = ConcurrentMapCache.getInstance().getAndRemove(deviceId+"_"+CommandEnum.GETIMEID.name()+"_"+payloadArr[4]);
        String messageId = messageIdObj==null?null:messageIdObj.toString();
        if(messageId==null){
            messageId = deviceId+"_"+payloadArr[4];
        }

        report.setFunctionId(CommandEnum.GETIMEID.name());
        report.setMessageId(messageId);
        report.setTimestamp(System.currentTimeMillis());
        Map<String, Object> properties = new HashMap<>();
        properties.put("uptime",payloadArr[5]);
        properties.put("meid",payloadArr[6]);
        properties.put("s",payloadArr[7]);
        properties.put("latitude",BinaryUtils.getWgs84LonLat(payloadArr[8],"lat"));
        properties.put("d",payloadArr[9]);
        properties.put("longitude",BinaryUtils.getWgs84LonLat(payloadArr[10],"lon"));
        properties.put("g",payloadArr[11]);
        properties.put("speed", NumberUtils.parseDouble(payloadArr[12]));
        properties.put("pdop",NumberUtils.parseDouble(payloadArr[13]));
        properties.put("upday", payloadArr[14]);
        String trackerStatusHex = payloadArr[15];


        Map<String,Object> trackerStatusMap = parseTrackerStatus(trackerStatusHex);
        properties.put("trackerstatus",trackerStatusMap);
        report.setOutput(properties);

        //TODO 更新状态
        return genDeviceMessage(report);
    }

    @Override
    public EncodedMessage encodeMessage(CommonDeviceMessage message,String zzs) {
        //平台下发消息
        //格式：*XX,YYYYYYYYYYYYYYY,GETIMEID,HHMMSS#
        //例子：*TJ,86954789991234566958,GETIMEID,130305#
        String time = SxlMessageUtils.getTimeHHMMSS();//DateFormatUtils.format(new Date(),"HHmmss");
        /*StringBuffer sb = new StringBuffer();
        sb.append("*");
        sb.append(zzs);//TODO 需要修改成根据设备动态加载
        sb.append(",");
        sb.append(message.getDeviceId());
        sb.append(",");
        sb.append(CommandEnum.GETIMEID.name());
        sb.append(",");
        sb.append(time);
        sb.append("#");*/
        ConcurrentMapCache.getInstance().set(message.getDeviceId()+"_"+CommandEnum.GETIMEID.name()+"_"+time,message.getMessageId(),60*3*1000);
       // return EncodedMessage.simple(Unpooled.wrappedBuffer(sb.toString().getBytes()));

        return SxlMessageUtils.SxlCmd.getInstance()
            .appendAndAddSeparator(zzs)
            .appendAndAddSeparator(message.getDeviceId())
            .appendAndAddSeparator(CommandEnum.GETIMEID.name())
            .append(time).buildEncodeMessage();
    }
}
